<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
		<title></title>
	</head>
	<body>
		<input type="text" name="name" id="name" value="wangwu" />
		<input type="text" name="pw" id="pw" value="123456" />
		<input type="text" name="tags" id="tags" value="js,vue" />
		<div></div>
		<button type="button" id="login">登录</button>
		<button type="button" id="query">查询数据库</button>
		<input type="file" name="file" id="file" value="" />
		<input type="button" name="btn" id="btn" value="提交" />
		<script type="text/javascript">
			$(function() {
				if (localStorage.getItem('token')) {
					console.log('有token');
				} else {
					console.log('没有token');
				}
				let login = $('#login')
				let query = $('#query')
				let file = $('#file')
				let btn = $('#btn')
				let loginUrl = 'http://localhost:3000/user/login'
				let queryUrl = 'http://localhost:3000/blog/getBlogs'
				let updateUrl = 'http://localhost:3000/update/test'
				login.click(function() {
					let name = $('#name').val()
					let pw = $('#pw').val()
					getData({
						username: name,
						password: pw
					}, loginUrl, (res) => {
						console.log(res)
						localStorage.setItem('token', res.data.token)
					})
				})
				query.click(function() {
					let tags = $('#tags').val()
					getData({
						tags
					}, queryUrl, (res) => {
						console.log(res)
					})
				})
				btn.click(function() {
					console.log($('#file').prop('files')[0]);
					var forData = new FormData();
					forData.append("files", $('#file').prop('files')[0]);
					updateFile({
						filename: '123123',
						file: forData
					}, updateUrl, (res) => {
						console.log(res);
					})
				})
			
				function getData(data, url, cb) {
					let headers = {}
					if (localStorage.getItem('token')) {
						headers = {
							'authorization': "Bearer " + localStorage.getItem('token')
						}
					}
					$.ajax({
						url,
						type: 'POST',
						dataType: 'json',
						headers,
						data,
						cache: false,
						  processData: false,
						  contentType: false,
						success: function(e) {
							cb(e)
						},
						error: function(err) {
							console.log(err);
						}
					})
				}
				
				function updateFile(data, url, cb) {
					let headers = {}
					if (localStorage.getItem('token')) {
						headers = {
							'authorization': "Bearer " + localStorage.getItem('token')
						}
					}
					$.ajax({
						url,
						type: 'POST',
						dataType: 'json',
						headers,
						data,
						cache: false,
						processData: false,
						contentType: false,
						success: function(e) {
							cb(e)
						},
						error: function(err) {
							console.log(err);
						}
					})
				}
			})
		</script>
	</body>
</html>
